package cn.cdeden.job.snailjob.snailjob;

import cn.cdeden.job.snailjob.snailjob.domain.AdDepartment;
import cn.cdeden.job.snailjob.snailjob.domain.enums.AdRegionConstant;
import cn.cdeden.job.snailjob.snailjob.service.LdapSevice;
import cn.cdeden.job.snailjob.snailjob.service.SyncDepartmentService;
import cn.cdeden.system.api.RemoteDeptService;
import cn.cdeden.system.api.RemoteLgtypeConfigService;
import cn.cdeden.system.api.RemoteUserService;
import cn.cdeden.system.api.domain.vo.RemoteDeptVo;
import cn.cdeden.system.api.domain.vo.RemoteUserVo;
import com.aizuda.snailjob.client.job.core.dto.JobArgs;
import com.aizuda.snailjob.client.job.core.executor.AbstractJobExecutor;
import com.aizuda.snailjob.client.model.ExecuteResult;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Component;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
import java.util.*;

/**
 * AD域控 组织架构同步
 */
@Component
@RequiredArgsConstructor
public class AdDomainJobExecutor  extends AbstractJobExecutor {

    @DubboReference
    private RemoteLgtypeConfigService remoteLgtypeConfigService;

    private final LdapSevice ldapSevice;

    private final SyncDepartmentService syncDepartmentService;


    private static final String LOGIN_TYPE = "ad";
    private static final String AD_DOMAIN_URL_KEY = "ad_domain_url";


    @Override
    protected ExecuteResult doJobExecute(JobArgs jobArgs) {

        //获取AD域配置
        Map<String, String> config = remoteLgtypeConfigService.getAllConfigByKeys(LOGIN_TYPE);

        String ldapUrl = config.get(AD_DOMAIN_URL_KEY);
        if (ldapUrl == null || ldapUrl.isEmpty()) {
            return ExecuteResult.failure("AD验证失败：LDAP配置信息缺失");
        }

        try {
            // 获取Ldap上下文接口
            LdapContext ldapContext = ldapSevice.ldapConnect(config);

            // 获取所有部门和人员信息并进行同步
            syncDepartmentService.syncDepartmentsAndUsers(ldapContext, config);

            //向其它子系统发送同步通知
//            coreRabbitMqService.send2Tms(JSONObject.toJSONString(adDomainConfig));

            ldapContext.close();
        } catch (NamingException e) {
//            logger.endOperation("FAILED", "AD域同步失败: " + e.getMessage());
            throw new RuntimeException(e);
        }

        return ExecuteResult.success("TestJobExecutor测试成功");
    }

}
